package com.kiss.rpc.channelhandler.handler;

import com.kiss.rpc.compress.Compressor;
import com.kiss.rpc.compress.CompressorFactory;
import com.kiss.rpc.serialize.Serializer;
import com.kiss.rpc.serialize.SerializerFactory;
import com.kiss.rpc.transport.message.MessageFormatConstant;
import com.kiss.rpc.transport.message.RpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RpcResponseEncoder extends MessageToByteEncoder<RpcResponse> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse, ByteBuf byteBuf) {
        byteBuf.writeBytes(MessageFormatConstant.MAGIC);
        byteBuf.writeByte(MessageFormatConstant.VERSION);

        byteBuf.writeShort(MessageFormatConstant.HEADER_LENGTH);
        byteBuf.writerIndex(byteBuf.writerIndex() + MessageFormatConstant.FULL_FIELD_LENGTH);

        byteBuf.writeByte(rpcResponse.getCode());
        byteBuf.writeByte(rpcResponse.getSerializeType());
        byteBuf.writeByte(rpcResponse.getCompressType());

        byteBuf.writeLong(rpcResponse.getRequestId());
        byteBuf.writeLong(rpcResponse.getTimeStamp());

        byte[] body = null;
        if (rpcResponse.getBody() != null) {
            Serializer serializer = SerializerFactory.getSerializer(rpcResponse.getSerializeType()).getImpl();
            body = serializer.serialize(rpcResponse.getBody());
            Compressor compressor = CompressorFactory.getCompressor(rpcResponse.getCompressType()).getImpl();
            body = compressor.compress(body);
        }

        CommonFuncs.writeFullLength(byteBuf, body);

        if (log.isDebugEnabled()) {
            log.debug("响应【{}】已经在服务端完成编码工作。", rpcResponse.getRequestId());
        }
    }


}
